<script setup>
import api from '@/api';
import utils from '@/utils';
import { onMounted, ref, watch } from 'vue';


const emits = defineEmits(['cancel', 'submit'])
const props = defineProps({
  editData: {
    type: Object,
    default: null
  },
  editBaseMessage: {
    type: Boolean,
    default: false
  }
});

const tunnelForm = ref({
  name: '',
  sshTunnelId: '',
  localPort: '',
  remoteHost: '',
  remotePort: '',
  tags: [],
  url: '',
});
watch(() => props.editData, handleReset, { immediate: true });

// SSH主机选项
const sshHostOptions = ref([
]);

onMounted(async () => {
  const res = await api.sshTunnel.getSshTunnelList();
  sshHostOptions.value = res.data;
});

// 标签选项
const tagsOptions = ref([]);

onMounted(async () => {
  const res = await api.tag.getTagList();
  tagsOptions.value = res.data.map(item => item.name);
});




// 表单验证规则
const formRules = {
  remoteHost: [
    { required: true, message: '请输入远程ip', trigger: 'blur' },
    { pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: '请输入正确的ip地址', trigger: 'blur' }
  ],
  remotePort: [
    { required: true, message: '请输入远程端口', trigger: 'blur' },
    utils.validation.positiveIntegerRule
  ],
  localPort: [
    { required: true, message: '请输入本地端口', trigger: 'blur' },
    utils.validation.positiveIntegerRule
  ],
  sshTunnelId: [
    { required: true, message: '请选择SSH隧道', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入端口转发名称', trigger: 'blur' }
  ],
};

// 表单引用
const formRef = ref(null);

// handleChange
function handleChangeRemotePort(value) {
  tunnelForm.value.localPort = value;
}

// handleCancle
function handleCancle() {
  emits('cancel')
}

// handleSave
async function handleSave() {
  await utils.validation.validateForm(formRef.value)
  // 将数组tags转换为逗号分隔的字符串（发送给后端）
  const submitData = {
    ...tunnelForm.value,
    tags: Array.isArray(tunnelForm.value.tags) ? tunnelForm.value.tags.join(',') : (tunnelForm.value.tags || '')
  };
  if (!!props.editData?.id) {
    if (props.editBaseMessage) {
      await api.portLocalForward.editPortLocalForwardBaseMessage(submitData);
    } else {
      await api.portLocalForward.editPortLocalForward(submitData);
    }
    utils.message.success('编辑成功');
  } else {
    await api.portLocalForward.addPortLocalForward(submitData);
    utils.message.success('新增成功');
  }
  emits('submit')
}

function handleReset() {
  tunnelForm.value = {
    id: props.editData?.id || '',
    name: props.editData?.name || '',
    sshTunnelId: props.editData?.sshTunnelId || '',
    localPort: props.editData?.localPort || '',
    remoteHost: props.editData?.remoteHost || '',
    remotePort: props.editData?.remotePort || '',
    url: props.editData?.url || '',
    tags: props.editData?.tags && props.editData?.tags.length > 0 ? props.editData?.tags : [] || [],
  };
}

</script>

<template>
  <el-form :model="tunnelForm" label-width="auto" :rules="formRules" ref="formRef">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="端口转发名称" prop="name">
          <el-input v-model="tunnelForm.name" placeholder="请输入端口转发名称" />
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="!editBaseMessage">
        <el-form-item label="远程ip" prop="remoteHost">
          <el-input v-model="tunnelForm.remoteHost" placeholder="请输入远程ip" />
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="!editBaseMessage">
        <el-form-item label="远程端口" prop="remotePort">
          <el-input v-model="tunnelForm.remotePort" placeholder="请输入远程端口" @change="handleChangeRemotePort" />
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="!editBaseMessage">
        <el-form-item label="本地端口" prop="localPort">
          <el-input v-model="tunnelForm.localPort" placeholder="请输入本地端口" />
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="!editBaseMessage">
        <el-form-item label="SSH隧道" prop="sshTunnelId">
          <el-radio-group v-model="tunnelForm.sshTunnelId">
            <el-radio v-for="item in sshHostOptions" :key="item.id" :label="item.id">
              {{ item.name }} {{ item.username }}@{{ item.host }}:{{ item.port }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="访问地址" prop="url">
          <el-input type="textarea" v-model="tunnelForm.url"
            :placeholder="`默认：http://localhost:${tunnelForm.localPort}/`" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="标签" prop="tags">
          <el-checkbox-group v-model="tunnelForm.tags">
            <el-checkbox v-for="item in tagsOptions" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <div class="dialog-footer">
    <el-button @click="handleCancle">取消</el-button>
    <el-button type="primary" @click="handleSave">确定</el-button>
    <el-button @click="handleReset">重置</el-button>
  </div>
</template>

<style scoped lang="scss"></style>
